package com.smt.common.utils;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.smt.common.enums.Code;
import com.smt.modules.bus.entity.BillEntity;
import com.smt.modules.bus.entity.GradeEntity;
import com.smt.modules.bus.entity.MemberUserEntity;
import com.smt.modules.bus.entity.TeamEntity;
import com.smt.modules.bus.service.BillService;
import com.smt.modules.bus.service.GradeService;
import com.smt.modules.bus.service.MemberUserService;
import com.smt.modules.bus.service.TeamManagementService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一添加账单工具类
 *
 * @author zhangyi
 * @date 2018/10/18 10:11
 */
@Component
@Slf4j
public class BillUtils {

    @Autowired
    private BillService billService;

    @Autowired
    private GradeService gradeService;

    @Autowired
    private TeamManagementService teamManagementService;

    @Autowired
    private MemberUserService memberUserService;



    /**
     * 公司信息修改添加账单
     *
     * @param billEntity
     * @param memberUserEntity
     */
    public boolean addBills(BillEntity billEntity, MemberUserEntity memberUserEntity,String operateType){
        billEntity.setCreateTime(DateTime.now().toDate());
        billEntity.setTransactionName(memberUserEntity.getEmail() == null ? memberUserEntity.getMobile() : memberUserEntity.getEmail());
        billEntity.setTransactionTime(DateTime.now().toDate());
        billEntity.setIsReward(1);
        //团队增加奖励
        if(operateType != null){
            if(operateType.equals(Constant.COMPANY_INTRODUCTION) ||
                    operateType.equals(Constant.COMPANY_CREATE) ||
                    operateType.equals(Constant.COMPANY_BUSINESS)){
                //获取该创建者下的所有成员信息
                List<TeamEntity> memberList =
                        teamManagementService.getMemberList(memberUserEntity.getUserId());
                memberList.stream()
                        .forEach(m -> {
                            if(!m.getMemberId().equals(memberUserEntity.getUserId())){
                                GradeEntity gE =
                                        gradeService.selectOne(new EntityWrapper<GradeEntity>()
                                                .eq("member_id", m.getMemberId()));
                                Integer oldIn = gE.getIntegral();
                                GradeEntity g = new GradeEntity();
                                BillEntity memberBill = new BillEntity();
                                if(operateType.equals(Constant.COMPANY_INTRODUCTION)){
                                    g.setIntegral(oldIn+50);
                                    memberBill.setAmount(50);
                                    memberBill.setBillTitle("编写公司简介，增加大家对公司的了解");
                                }else if(operateType.equals(Constant.COMPANY_CREATE) ){
                                    g.setIntegral(oldIn+300);
                                    memberBill.setAmount(300);
                                    memberBill.setBillTitle("创建一家公司");
                                }else if(operateType.equals(Constant.COMPANY_BUSINESS)){
                                    g.setIntegral(oldIn+500);
                                    memberBill.setAmount(500);
                                    memberBill.setBillTitle("上传公司的营业执照，保障企业的合法性");
                                }
                                //获取成员信息
                                MemberUserEntity memberUser=
                                        memberUserService
                                                .selectOne(new EntityWrapper<MemberUserEntity>()
                                                        .eq("user_id", m.getMemberId()));
                                //声场成员账单
                                memberBill.setTransactionName(memberUser.getUsername());
                                memberBill.setBusBusinessId(m.getMemberId());
                                memberBill.setCreateTime(DateTime.now().toDate());
                                memberBill.setTransactionTime(DateTime.now().toDate());
                                memberBill.setExpenditure(1);
                                memberBill.setIsReward(1);
                                memberBill.setType(1);
                                billService.insert(memberBill);
                                gradeService.update(g,
                                        new EntityWrapper<GradeEntity>()
                                                .eq("member_id",m.getMemberId()));
                            }
                        });
            }
        }
        boolean insert = true;
        //更新账单状态
        if(billEntity.getBillTitle().equals(Constant.TASK_5)){
            BillEntity b = new BillEntity();
            b.setIsReward(1);
            b.setCreateTime(DateTime.now().toDate());
            b.setTransactionName(memberUserEntity.getEmail() == null ? memberUserEntity.getMobile() : memberUserEntity.getEmail());
            b.setTransactionTime(DateTime.now().toDate());
            b.setType(1);
            b.setExpenditure(1);
            b.setBillTitle(Constant.TASK_5);
            b.setAmount(500);
            b.setBusBusinessId(memberUserEntity.getUserId());
            boolean update = billService.update(b, new EntityWrapper<BillEntity>().eq("bill_title", Constant.TASK_5)
                    .eq("bus_business_id", billEntity.getBusBusinessId()));
            if(!update){
                billService.update(b, new EntityWrapper<BillEntity>().eq("bill_title", Constant.TASK_5)
                        .eq("bus_business_id", b.getBusBusinessId()));
                insert = false;
            }
            log.info("公司营业执照更新状态 : {}",update);
        }
        boolean billFlag = false;
        if(insert) {
            billEntity.setBillTitle(null);
            billFlag = billService.updateById(billEntity);
        }
        return billFlag || insert;
    }

    /**
     * 消费账单
     *
     * @param title
     * @param amount
     * @param memberUserEntity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean ConsumptionFile(String title,Integer amount, Long consumptionId,MemberUserEntity memberUserEntity){
        Long userId = memberUserEntity.getUserId();
        String username = memberUserEntity.getUsername();
        //写入账单
        BillEntity billEntity = new BillEntity(title,amount,2,DateTime.now().toDate(),username,userId,DateTime.now().toDate(),0,2);
        billEntity.setFileLoadId(consumptionId);
        boolean insert = billService.insert(billEntity);
        //更新总积分
        GradeEntity gradeEntity = gradeService.selectOne(new EntityWrapper<GradeEntity>().eq("member_id", userId));
        Integer integral = gradeEntity.getIntegral();
        Integer newReward = integral - amount;
        gradeEntity.setIntegral(newReward);
        boolean b = gradeService.updateById(gradeEntity);
        return b && insert;
    }
}
